package com.sciencep.pro.common.utils;


import com.sciencep.pro.common.config.Constant;
import com.sciencep.pro.common.exception.CustomException;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.List;

public class ExportUtil {

    private ExportUtil() {

    }

    public static void exportExcelToReponse(HttpServletResponse response, LinkedHashMap<String, String> titleColumnMaps, List<?> dataList, String fileName, int[] size) throws CustomException, IOException {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PoiExcelExport excelExport = new PoiExcelExport(outputStream, "result");
        excelExport.writeExcel(titleColumnMaps, size, dataList);
        byte[] bytes = outputStream.toByteArray();
        InputStream is = new ByteArrayInputStream(bytes);

        String zhStr= "";
        try {
            zhStr = new String(fileName.getBytes(Constant.GB2312), StandardCharsets.ISO_8859_1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        response.setContentType("application/octet-stream");
        OutputStream out = response.getOutputStream();
        //使用URLEncoder来防止文件名乱码或者读取错误
        response.setHeader("Content-Disposition", "attachment; filename=" + zhStr + LocalDate.now() + ".xls");
        int b = 0;
        byte[] buffer = new byte[100000];
        while (b != -1) {
            b = is.read(buffer);
            if (b != -1) {
                out.write(buffer, 0, b);
            }
        }
        is.close();
        out.flush();
        out.close();

    }
}
